import util from '@/libs/util';
import CONSTANTS from '@/config/constants';
import Cookies from 'js-cookie';
import UEditor from '@/util/ueditor.vue';
import activityList from './activityList.vue';

export default {
    name: 'exportable-table',
    components: {UEditor, activityList},
    data () {
        return {
            columns: [{
                title: '序号',
                key: 'rownum',
                width: 60,
                align: 'center',
                render: (h, params) => {
                    return h('div', {}, ((this.pageIndex - 1) * this.pageSize + params.index + 1));
                }
            }, {
                title: '文章标题',
                key: 'title',
                render: (h, params) => {
                    return h('Tooltip', {
                        props: {
                            content: params.row.title
                        }
                    }, params.row.title);
                }
            }, {
                title: '活动名称',
                key: 'articleid',
                ellipsis: true,
                render: (h, params) => {
                    return h('Tooltip', {
                        props: {
                            placement: 'top-start',
                            content: params.row.activity.name
                        }
                    }, params.row.activity.name);
                }
            }, {
                title: '封面',
                key: 'cover',
                render: (h, params) => {
                    let imgpath = this.SERVER_HOST + params.row.cover;
                    return h('img', {
                        style: {
                            height: '60px'
                        },
                        attrs: {
                            src: imgpath
                        },
                        on: {
                            click: () => {
                                this.imgUrl = imgpath;
                                this.imgModal = true;
                            }
                        }
                    });
                }
            }, {
                title: '文章摘要',
                key: 'summary',
                render: (h, params) => {
                    return h('Tooltip', {props: {placement: 'top-start'}}, [
                        h('div', {style: {'white-space': 'nowrap'}}, params.row.summary),
                        h('div', {slot: 'content', style: {'white-space': 'normal'}}, params.row.summary)
                    ]);
                }
            }, {
                title: '是否发布',
                key: 'releases',
                render: (h, params) => {
                    return h('div', {}, (params.row.releases === 1 ? '是' : '否'));
                }
            }, {
                title: '操作',
                key: 'action',
                width: 300,
                align: 'center',
                render: (h, params) => {
                    return h('div', [
                        h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: () => {
                                    this.release(params.row.id, params.row.releases);
                                }
                            }
                        }, (params.row.releases === 1 ? '取消发布' : '发布')),
                        h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: () => {
                                    this.detail(params.row.id);
                                }
                            }
                        }, '详情'),
                        h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: () => {
                                    this.showEdit(params.row);
                                }
                            }
                        }, '修改'),
                        h('Button', {
                            props: {
                                type: 'error',
                                size: 'small'
                            },
                            on: {
                                click: () => {
                                    this.delete(params.row.id);
                                }
                            }
                        }, '删除')
                    ]);
                }
            }],
            baseuser: JSON.parse(Cookies.get('baseUser')),
            SERVER_HOST: CONSTANTS.SERVER_HOST,
            config: {
                scaleEnabled: true,
                autoFloatEnabled: true,
                initialContent: '',
                autoClearinitialContent: true,
                initialFrameWidth: null,
                initialFrameHeight: 450,
                BaseUrl: '',
                UEDITOR_HOME_URL: '/static/ueditor/'
            },
            data: [],
            formData: {},
            viewModalVisible: false,
            saveModalVisible: false,
            imgModal: false,

            total: 0,
            pageIndex: 1,
            pageSize: 10,
            queryCon: {},
            uploadList: [],
            imgUrl: '',
            activityModal: false,
            ruleValidate: {
                title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
                activityname: [{ required: true, message: '请选择活动', trigger: 'blur' }]
            }
        };
    },
    mounted () {
        this.loadList();
    },
    methods: {
        loadList () {
            util.ajax.post('/busine/article/list', util.toFormData({
                page: this.pageIndex,
                size: this.pageSize,
                title: this.queryCon.title ? this.queryCon.title : '',
                activityname: this.queryCon.activityname ? this.queryCon.activityname : '',
                releases: this.queryCon.releases ? this.queryCon.releases : '',
                userid: this.baseuser.id
            })).then(res => {
                this.data = res.data.data.list;
                this.total = res.data.data.total;
            });
        },
        detail (id) {
            util.ajax.post('/busine/article/detail', util.toFormData({
                id: id
            })).then(res => {
                if (res.data.data) {
                    let data = res.data.data;
                    data['imgUrl'] = this.SERVER_HOST + data.cover;
                    this.formData = data;
                    this.viewModalVisible = true;
                } else {
                    this.$Modal.error({
                        title: '警告',
                        content: '出错了'
                    });
                }
            });
        },
        showAdd () {
            this.formData = {};
            this.uploadList = [];
            this.$refs.article_intro.setUEContent('');
            this.saveModalVisible = true;
        },
        showEdit (obj) {
            this.formData = {};
            util.ajax.post('/busine/article/detail', util.toFormData({
                id: obj.id
            })).then(res => {
                if (res.data.data) {
                    this.formData = res.data.data;
                    this.imgUrl = this.SERVER_HOST + this.formData.cover;
                    if (this.formData.cover) {
                        this.uploadList = [{
                            status: 'finished',
                            showProgress: true,
                            url: this.imgUrl
                        }];
                    } else {
                        this.uploadList = [];
                    }
                    this.formData.activityname = this.formData.activity.name;
                    this.$refs.article_intro.setUEContent(this.formData.content);
                    this.saveModalVisible = true;
                } else {
                    this.$Modal.error({
                        title: '警告',
                        content: '出错了'
                    });
                }
            });
        },
        save () {
            this.$refs.formSave.validate((valid) => {
                if (valid) {
                    let formData = {};
                    for (let key in this.formData) {
                        formData[key] = this.formData[key];
                    }
                    formData['content'] = this.$refs.article_intro.getUEContent();
                    formData['userid'] = this.baseuser.id;
                    util.ajax.post('/busine/article/save', util.toFormData(formData)).then(res => {
                        if (res.data.message === 'SUCCESS') {
                            this.saveModalVisible = false;
                            this.$Message.success('保存成功！');
                            this.loadList();
                        } else {
                            this.$Message.warning(res.data.message || '未知错误！');
                        }
                    });
                }
            });
        },
        handleReset () {
            this.saveModalVisible = false;
            this.$refs.formSave.resetFields();
        },
        delete (id) {
            this.$Modal.confirm({
                title: '提示',
                content: '<p>确定删除？</p>',
                onOk: () => {
                    util.ajax.post('/busine/article/delete', util.toFormData({
                        id: id
                    })).then(res => {
                        if (res.data.message === 'SUCCESS') {
                            this.$Message.success('删除成功！');
                            this.loadList();
                        }
                    });
                },
                onCancel: () => {
                }
            });
        },
        handleSuccess (res, file) {
            this.uploadList = [{
                showProgress: true
            }]
            var xmlhttp = null;
            var urlPath = this.SERVER_HOST + res.data.imgUrl;
            if (window.XMLHttpRequest) {
                xmlhttp = new XMLHttpRequest();
            }
            let interval = setInterval(() => {
                xmlhttp.open('GET', urlPath, false);
                xmlhttp.send();
                if ((xmlhttp.readyState === 4 && xmlhttp.status === 200)) {
                    clearInterval(interval);
                    this.$Notice.success({
                        title: '文件上传成功',
                        desc: '文件 ' + file.name + ' 上传成功。',
                        duration: 2
                    });
                    file.url = this.SERVER_HOST + res.data.imgUrl;
                    file.name = res.data.fileName;
                    this.uploadList = this.$refs.upload.fileList;
                    this.formData.cover = res.data.imgUrl;
                    this.imgUrl = this.SERVER_HOST + res.data.imgUrl;
                }
            }, 500);
        },
        handleFormatError (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请选择图片文件。',
                duration: 5
            });
        },
        handleMaxSize (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。',
                duration: 5
            });
        },
        handleRemove (file) {
            this.uploadList = [];
            this.$refs.upload.fileList = [];
            this.formData.cover = '';
        },
        handleBeforeUpload () {
            const check = this.uploadList.length < 1;
            if (!check) {
                this.$Notice.warning({
                    title: '最多只能上传 1 张图片。',
                    duration: 5
                });
            }
            return check;
        },
        refresh () {
            this.queryCon = {};
            this.loadList();
        },
        openImg (imgPath) {
            this.imgUrl = imgPath;
            this.imgModal = true;
        },
        selectActivity () {
            this.activityModal = true;
        },
        setActivity () {
            let activity = this.$refs.activity.activity;
            if (activity.name && activity.id) {
                this.formData.activityname = activity.name;
                this.formData.activityid = activity.id;
            }
            this.activityModal = false;
        },
        release (id, releases) {
            util.ajax.post('/busine/article/detail', util.toFormData({
                id: id
            })).then(res => {
                if (res.data.data) {
                    this.formData = res.data.data;
                    this.formData.releases = 1;
                    if (releases == 1) this.formData.releases = 2;
                    util.ajax.post('/busine/article/save', util.toFormData(this.formData)).then(res => {
                        if (res.data.message === 'SUCCESS') {
                            this.$Message.success('文章发布修改成功！');
                            this.loadList();
                        }
                    });
                } else {
                    this.$Modal.error({
                        title: '警告',
                        content: '出错了'
                    });
                }
            });
        }
    }
};